package gl.android.biyiqing.competent;

import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.api.API;
import gl.android.biyiqing.event.ReadMsg;
import gl.android.biyiqing.fragment.BaseFragment;
import gl.android.biyiqing.fragment.MessageChatFragment;
import gl.android.biyiqing.fragment.ShopFragment;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.AndroidUtil;
import gl.uitls.GsonUtils;
import gl.uitls.Tip;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.huewu.pla.lib.internal.PLA_AdapterView;

import de.greenrobot.event.EventBus;

public class OnMsgItemClickListener implements OnItemClickListener,
		com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener {

	private String jsonArrayData;
	private Object[] pars;
	private int msgType;
	private Context Context;

	public OnMsgItemClickListener(String jsonArrayData, int msgType) {
		this.msgType = msgType;
		this.jsonArrayData = jsonArrayData;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Context = arg1.getContext();
		goUserInfoActivity(arg2);
	}

	private String ERR = "邮票不足,读取信件失败";
	private String NOTFOUND = "读取信件失败";

	private void goUserInfoActivity(int arg2) {
		try {
			ArrayList<HashMap<String, String>> map = GsonUtils
					.JSON2MapArrayList(new JSONObject(jsonArrayData)
							.getJSONArray("data"));
			String msgid = map.get(arg2).get("msgid");
			switch (msgType) {
			case 0:
				readSysMsg(arg2, map, msgid);
				break;
			case 1:
				readPriMsg(arg2, map, msgid);
				break;
			case 2:
				readReadAlreadyMsg(arg2, map, msgid);
				break;
			case 3:
				readSendAlreadyMsg(arg2, map, msgid);
				break;
			default:
				break;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取未读消息
	 * 
	 * @param arg2
	 * @param map
	 * @param msgid
	 */
	private void readPriMsg(int arg2, ArrayList<HashMap<String, String>> map,
			String msgid) {
		final HashMap<String, String> hashMap = map.get(arg2);
		if (beforeReadMessage(hashMap)) {
			return;
		}
		readMessage(hashMap);

	}

	public void readMessageByPost(final HashMap<String, String> hashMap) {
		final String fromuserid = hashMap.get("fromuserid");
		String msgcount = hashMap.get("msgcount");
		String sendtime = hashMap.get("sendtime");
		String msgid1 = hashMap.get("msgid");
		pars = new String[] {  UserManger.getInstance().userid,
				fromuserid, msgcount, sendtime };
		final String uri = API.URL
				+ "ReadMessage4Post?localuserid=%s&fromuserid=%s&msgcount=%s&sendtime=%s";
		BaseControl
				.get(uri,
						new AjaxCallBackProxy() {

							@Override
							public void onSuccess(String t) {
								super.onSuccess(t);
								try {
									handErrMsg(t);
									if ("2".equals(new JSONObject(t)
											.getString("msg"))) {
										Intent intent = new Intent(Context,
												FragmentContainerActivity.class);
										Bundle bundle = new Bundle();
										bundle.putString(
												BaseFragment.KEY_JSON_DATA, t);
										bundle.putString(
												BaseFragment.KEY_TO_USER_ID,
												fromuserid);
										bundle.putString(
												"uri",
												String.format(API.URL
														+ "ReadSendMessage?msgid=%s&localuserid=%s&fromuserid=%s&sendtime=%s", pars));
										bundle.putString(
												FragmentContainerActivity.BaseFragmentClassName,
												MessageChatFragment.class
														.getName());
										intent.putExtras(bundle);
										Context.startActivity(intent);
										EventBus.getDefault().post(new ReadMsg());
										return;
									}else{
										Tip.show(ERR);
									}

								} catch (Exception e) {
									e.printStackTrace();
									onFailure(e, 0, e.getMessage());
								}
							}

							@Override
							public void onFailure(Throwable t, int errorNo,
									String strMsg) {
								super.onFailure(t, errorNo, strMsg);
								Tip.show(ERR);
							}
						}, pars);
	}
	public void readMessage(final HashMap<String, String> hashMap) {
		final String fromuserid = hashMap.get("fromuserid");
		String msgcount = hashMap.get("msgcount");
		String sendtime = hashMap.get("sendtime");
		String msgid1 = hashMap.get("msgid");
		pars = new String[] {UserManger.getInstance().userid,
				fromuserid, msgcount, sendtime };
		final String uri = API.URL
				+ "ReadMessage?localuserid=%s&fromuserid=%s&msgcount=%s&sendtime=%s";
		BaseControl
		.get(uri,
				new AjaxCallBackProxy() {
			
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				try {
					handErrMsg(t);
					if ("2".equals(new JSONObject(t)
					.getString("msg"))) {
						EventBus.getDefault().post(new ReadMsg());
						Intent intent = new Intent(Context,
								FragmentContainerActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString(
								BaseFragment.KEY_JSON_DATA, t);
						bundle.putString(
								BaseFragment.KEY_TO_USER_ID,
								fromuserid);
						bundle.putString(
								"uri",
								String.format(API.URL
										+ "ReadSendMessage?msgid=%s&localuserid=%s&fromuserid=%s&sendtime=%s", pars));
						bundle.putString(
								FragmentContainerActivity.BaseFragmentClassName,
								MessageChatFragment.class
								.getName());
						intent.putExtras(bundle);
						Context.startActivity(intent);
						
						return;
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(e, 0, e.getMessage());
				}
			}
			
			@Override
			public void onFailure(Throwable t, int errorNo,
					String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				Tip.show(ERR);
			}
		}, pars);
	}

	/**
	 * 
	 * @param hashMap
	 * @return 是否打断读信流程
	 */
	private boolean beforeReadMessage(final HashMap<String, String> hashMap) {
		// 当SMSmothly=0 并且 SMShashid=0 时提示 【看信包月】 和 【贴邮票看信】 按键
		// 当点击【看信包月】，进入购买界面 当点击【贴邮票看信】则进入看信流程
		final String SMSmothly = hashMap.get("SMSmothly");
		final String SMShashid = hashMap.get("SMShashid");
		try {
			if (Integer.parseInt(SMSmothly) == 0
					&& Integer.parseInt(SMShashid) == 0) {
				new AlertDialog.Builder(Context)
						.setMessage("请选择看信方式")
						.setPositiveButton("看信包月",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
										Intent intent = new Intent(Context,
												FragmentContainerActivity.class);
										Bundle bundle = new Bundle();
										bundle.putString(
												FragmentContainerActivity.BaseFragmentClassName,
												ShopFragment.class.getName());
										intent.putExtras(bundle);
										Context.startActivity(intent);
									}
								})
						.setNegativeButton("贴邮票看信",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
										readMessageByPost(hashMap);
									}
								}).setTitle("初次通信").show();
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	private void readSendAlreadyMsg(int arg2,
			ArrayList<HashMap<String, String>> map, String msgid) {

		final String touserid = map.get(arg2).get("touserid");
		// String msgcount = map.get(arg2).get("msgcount");
		String sendtime = map.get(arg2).get("sendtime");
		pars = new String[] { msgid, UserManger.getInstance().userid,
				touserid/* , msgcount */, sendtime };
		final String uri = API.URL
				+ "ReadSendMessage?msgid=%s&localuserid=%s&fromuserid=%s&sendtime=%s";
		BaseControl
				.get(uri,
						new AjaxCallBackProxy() {

							@Override
							public void onSuccess(String t) {
								super.onSuccess(t);
								try {
									handErrMsg(t);
									if ("2".equals(new JSONObject(t)
											.getString("msg"))) {
										Intent intent = new Intent(Context,
												FragmentContainerActivity.class);
										Bundle bundle = new Bundle();
										bundle.putString(
												BaseFragment.KEY_JSON_DATA, t);
										bundle.putString(
												BaseFragment.KEY_TO_USER_ID,
												touserid);
										bundle.putString(
												"uri",
												String.format(API.URL
														+ "ReadSendMessage?msgid=%s&localuserid=%s&fromuserid=%s&sendtime=%s", pars));
										bundle.putString(
												FragmentContainerActivity.BaseFragmentClassName,
												MessageChatFragment.class
														.getName());
										intent.putExtras(bundle);
										Context.startActivity(intent);
										return;
									}

								} catch (Exception e) {
									e.printStackTrace();
									onFailure(e, 0, e.getMessage());
								}
							}

							@Override
							public void onFailure(Throwable t, int errorNo,
									String strMsg) {
								super.onFailure(t, errorNo, strMsg);
								Tip.show(ERR);
							}
						}, pars);

	}

	private void readReadAlreadyMsg(int arg2,
			ArrayList<HashMap<String, String>> map, String msgid) {
		final String fromuserid = map.get(arg2).get("fromuserid");
		String msgcount = map.get(arg2).get("msgcount");
		String sendtime = map.get(arg2).get("sendtime");
		pars = new String[] { msgid, UserManger.getInstance().userid,
				fromuserid, msgcount, sendtime };
		final String uri = API.URL
				+ "ReadAlreadyMessage?msgid=%s&localuserid=%s&fromuserid=%s&msgcount=%s&sendtime=%s";
		BaseControl
				.get(uri,
						new AjaxCallBackProxy() {

							@Override
							public void onSuccess(String t) {
								super.onSuccess(t);
								try {
									handErrMsg(t);
									if ("2".equals(new JSONObject(t)
											.getString("msg"))) {
										Intent intent = new Intent(Context,
												FragmentContainerActivity.class);
										Bundle bundle = new Bundle();
										bundle.putString(
												BaseFragment.KEY_JSON_DATA, t);
										bundle.putString(
												BaseFragment.KEY_TO_USER_ID,
												fromuserid);
										bundle.putString(
												"uri",
												String.format(API.URL
														+ "ReadSendMessage?msgid=%s&localuserid=%s&fromuserid=%s&sendtime=%s", pars));
										bundle.putString(
												FragmentContainerActivity.BaseFragmentClassName,
												MessageChatFragment.class
														.getName());
										intent.putExtras(bundle);
										Context.startActivity(intent);
										return;
									}

								} catch (Exception e) {
									e.printStackTrace();
									onFailure(e, 0, e.getMessage());
								}
							}

							@Override
							public void onFailure(Throwable t, int errorNo,
									String strMsg) {
								super.onFailure(t, errorNo, strMsg);
								Tip.show(ERR);
							}
						}, pars);

	}

	private void readSysMsg(int arg2, ArrayList<HashMap<String, String>> map,
			String msgid) {
		pars = new String[] { msgid };
		final String title = map.get(arg2).get("subject");
		BaseControl.get(API.URL + "ReadSystemMessage?msgid=%s",
				new AjaxCallBackProxy() {

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							handErrMsg(t);
							if ("2".equals(new JSONObject(t).getString("msg"))) {
								ArrayList<HashMap<String, String>> map2 = GsonUtils
										.JSON2MapArrayList(new JSONObject(t)
												.getJSONArray("data"));
								String message = map2.get(0).get("content");
								AndroidUtil.genTipDialog(Context, message,
										title);
								return;
							}

						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Tip.show(ERR);
					}
				}, pars);
	}

	@Override
	public void onItemClick(PLA_AdapterView<?> parent, View view, int position,
			long id) {
		goUserInfoActivity(position);
	}

	private void handErrMsg(String t) throws JSONException {
		if ("0".equals(new JSONObject(t).getString("msg"))) {
			Tip.show(NOTFOUND);
			return;
		}
		if ("1".equals(new JSONObject(t).getString("msg"))) {
			Tip.show(ERR);
			AndroidUtil.genDialog(Context, "是否购买邮票", ERR,
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Intent intent = new Intent(Context,
									FragmentContainerActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString(
									FragmentContainerActivity.BaseFragmentClassName,
									ShopFragment.class.getName());
							intent.putExtras(bundle);
							Context.startActivity(intent);
						}
					});
			return;
		}
	}

}
